package com.tarim.streetdance.service.impl;

import com.tarim.streetdance.mapper.VideoViewsMapper;
import com.tarim.streetdance.model.Video;
import com.tarim.streetdance.model.VideoViews;
import com.tarim.streetdance.service.VideoService;
import com.tarim.streetdance.service.VideoViewsService;
import com.tarim.streetdance.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class VideoViewsServiceImpl implements VideoViewsService {
    @Autowired
    private VideoViewsMapper videoViewsMapper;
    @Autowired
    private VideoService videoService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertSelective(VideoViews record) {

        record.setDr(0);
        record.setCreateTime(new Date());

        //查询 视频 现有的 浏览数量
        Long viewsNum = this.selectCountByVideoId(record);

        //定义一个 视频 实体 用作修改 视频表 中的浏览数量
        Video video = new Video();
        //放入 视频ID
        video.setId(record.getVideoId());
        //放入 视频浏览量
        video.setViewsnum(viewsNum + 1);
        //进行修改操作
        videoService.updateForAddViewsnum(video);

        //删除旧记录，防止页面查看到重复数据
        videoViewsMapper.updateDeleteByUserIdAndVideoId(record);

        //最后 新增 浏览记录 到 视频浏览记录表 中
        return videoViewsMapper.insertSelective(record);
    }

    @Override
    public int updateForDelete(VideoViews record) {
        return videoViewsMapper.updateForDelete(record);
    }

    @Override
    public PageBean<VideoViews> selectByUserId(PageBean<VideoViews> pageBean, VideoViews record) {
        record.addExtField("pageIndex", pageBean.getPageIndex());
        record.addExtField("pageSize", pageBean.getPageSize());
        List<VideoViews> list = videoViewsMapper.selectByUserId(record);
        Long count = videoViewsMapper.selectByUserIdCount(record);
        pageBean.setTotalCount(count);
        pageBean.setData(list.toArray());
        return pageBean;
    }

    @Override
    public Long selectCountByVideoId(VideoViews record) {
        return videoViewsMapper.selectCountByVideoId(record);
    }
}